﻿using System;
using System.Collections.Generic;
using System.Text;
using Lon.IO;
using System.IO;
using Lon.Util;
using System.Threading;


namespace Lon.DataStore
{
    public class SaveServiceUseSqlite : IDataAccessService
    {
        private String directory;
      //  DBO yesterDayDb;
       // DBO todayDb;
 
        DateTime thisDay;
 //       UInt32 unixThisDay;



        public  SaveServiceUseSqlite(String path)
        {

            this.directory = path;

            thisDay = DateTime.Now.Date;

        
          
        }

        #region IDataSaveService 成员


        

        public void SaveConfigFile(String dbm, string fileName, uint createTime, uint modifyTime, uint accessTime, byte[] Content)
        {
           

            String fullPath = Path.Combine(directory, dbm+"\\Config\\Compatibility"+fileName);
            if (Directory.Exists(Path.GetDirectoryName(fullPath)) == false)
            {
                Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
            }
            File.WriteAllBytes(directory,Content);
            

        }

        public void SaveDayReport(int dbm, uint date, uint analogType, byte[] Content)
        {
         
        }

        public void SaveKgl(int dbm, uint dataTime, byte IsChange, byte[] Content)
        {
            
        }
        Queue<AlarmTable> alarmRecCache = new Queue<AlarmTable>();
        public void SaveAlarm(int dbm, uint type, uint startTime, string deviceName, byte[] Content)
        {
            
        }

        public byte[] ReadAllConfigFile(String dbm)
        {
            // string whereText = string.Format("WHERE ([RecTime] >= {0}) AND ([RecTime] <{1}) {2} ORDER BY [RecTime] DESC", TimeFormat.ToTickString(beginTime), TimeFormat.ToTickString(endTime), subText);


            string cfgRoot = Path.Combine(directory, "Config\\Compatibility");
         
       
          
            List<string> fileList = new List<string>();


         
             fileList.AddRange(GetMatchFiles(cfgRoot));
          
           
                return null;
            


        }


        public List<string> GetMatchFiles(string path)
        {
            List<string> fileList = new List<string>();
            if (Directory.Exists(path))
            {
                string[] files1 = Directory.GetFiles(path, "*.rhhcfg", SearchOption.TopDirectoryOnly);
                fileList.AddRange(FileFilter(files1));

                string[] files2 = Directory.GetFiles(path, "*.ini", SearchOption.TopDirectoryOnly);
                fileList.AddRange(FileFilter(files2));

                string[] files3 = Directory.GetFiles(path, "*.xml", SearchOption.TopDirectoryOnly);
                fileList.AddRange(FileFilter(files3));

                string[] files4 = Directory.GetFiles(path, "*.loncfg", SearchOption.TopDirectoryOnly);
                fileList.AddRange(FileFilter(files4));

            }

            return fileList;
        }

        public List<string> FileFilter(string[] files)
        {
            List<string> fileList = new List<string>();
            foreach (string fileName in files)
            {
                if (fileName.IndexOf("复件", 0) > 0) continue;
                fileList.Add(fileName);
            }

            return fileList;
        }

        //将文件列表里的配置文件合并为压缩后的字节数组
        public byte[] ZipConfigFiles(List<string> fileList)
        {
            if ((fileList == null) || (fileList.Count == 0)) { return null; }

            MemoryStream ms=new MemoryStream();
            BinaryWriter bw=new BinaryWriter(ms);

            bw.Write((int)fileList.Count);
            foreach (string fileName in fileList)
            {
                if (File.Exists(fileName))
                {
                    bw.Write(GetFileData(fileName));
                }
            }

            
         

            //压缩包
            byte[] tmpBuffer = ms.ToArray();
            byte[] zipBuffer = ZipHelper.ZipCompress(tmpBuffer, tmpBuffer.Length); //压缩

            return zipBuffer;
        }
        //将文件转换为字节数组
        private byte[] GetFileData(string fileName)
        {
            //Recorder i=文件名长度(4B)+文件名(实际长度)+文件大小(4B)+创建时间(4B)+修改时间(4B)+访问时间(4B)+文件内容（文件大小表示的字节数）
            if (!File.Exists(fileName)) { return null; }
            List<byte> valueList = new List<byte>();

            MemoryStream ms=new MemoryStream();
            BinaryWriter bw=new BinaryWriter(ms);
           
            FileInfo info = new FileInfo(fileName);
            byte[] tmpBytes = Encoding.Default.GetBytes(info.Name);
            bw.Write(tmpBytes.Length);

            bw.Write(tmpBytes);
            bw.Write((int)info.Length);

        
            bw.Write(DateTimeHelper.DateTime2UnixTime(info.CreationTime));      //创建时间(4B)
            bw.Write(DateTimeHelper.DateTime2UnixTime(info.LastWriteTime));    
            bw.Write(DateTimeHelper.DateTime2UnixTime(info.LastAccessTime));   
           

            //文件内容
            byte[] fileBytes = File.ReadAllBytes(fileName);
            bw.Write(fileBytes);

            return ms.ToArray();
        }

        public MemoryStream ReadConfigFile(int dbm, string fileName)
        {
                return null;
        }

        public MemoryStream ReadDayReport(int dbm, uint date,uint analogType)
        {
                return null;  
        }

        public MemoryStream[] ReadAllKgl(int dbm, uint startTime, uint endTime)
        {
           
                return null;
           
        }

   
        public MemoryStream[] ReadAlarm(int dbm, int type, uint startTime, uint endTime)
        {
           
                return null;
            
        }

        public MemoryStream[] ReadAlarm(int dbm, uint startTime, uint endTime)
        {
           
                return null;
            
        }

    



   

        public List<ConnectLogTable> ReadConnectLog(uint startTime, uint endTime)
        {

            return null;
        }

        public void SaveConnectLog(uint logTime, int id, string stationName, string dbm, string logMessage)
        {
            lock (this)
            {
                
                ConnectLogTable rec = new ConnectLogTable();
          
            }
        }
        Queue<DayReportTable> reportCache = new Queue<DayReportTable>();
        Queue<KglTable> kglCache = new Queue<KglTable>();
       
        void StoreProc()
        {
          
            Thread.Sleep(500);
        }

        public bool Start()
        {
            return true;
        }

        public bool Stop()
        {
            return true;
        }

        #endregion
    }


    public interface IDataAccessService
    {
        void SaveConfigFile(String dbm, String fileName, UInt32 createTime, UInt32 modifyTime, UInt32 accessTime, Byte[] Content);
        void SaveDayReport(int dbm, UInt32 date, UInt32 analogType, byte[] Content);
        void SaveKgl(int dbm, UInt32 dataTime, byte IsChange, byte[] Content);
        void SaveAlarm(int dbm, UInt32 type, UInt32 startTime, String deviceName, byte[] Content);
        /// <summary>
        /// 读取指定站的所有配置文件
        /// </summary>
        /// <param name="dbm"></param>
        /// <returns></returns>
        byte[] ReadAllConfigFile(String dbm);
     
        MemoryStream ReadDayReport(int dbm, UInt32 date,  UInt32 analogType);
        MemoryStream[] ReadAllKgl(int dbm, UInt32 startTime, UInt32 endTime);
        MemoryStream[] ReadAlarm(int dbm, int type, UInt32 startTime, UInt32 endTime);
        MemoryStream[] ReadAlarm(int dbm, UInt32 startTime, UInt32 endTime);
     
        List<ConnectLogTable> ReadConnectLog(UInt32 startTime, UInt32 endTime);
        void SaveConnectLog(UInt32 logTime, int id, String stationName, String dbm, String logMessage);
        bool Start();
        bool Stop();
    }
    public class DataAccessSeriveFactory
    {
        private static SaveServiceUseSqlite sqliteSaveService;
        private static object lockHandle = new object();
        public static IDataAccessService GetService(String seviceType)
        {
            lock (lockHandle)
            {
                if (sqliteSaveService != null) return sqliteSaveService;
                IniFile ini = new IniFile(Path.Combine(PathHelper.GetApplicationPath(), "Server.ini"));
                ini.Load();
                String storeDir = ini.GetString("存储", "位置");
                sqliteSaveService = new SaveServiceUseSqlite(storeDir);
                return sqliteSaveService;
            }
        }


    }

}

